package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.CommentType;
import com.itheima.util.ConstantUtil;
import com.itheima.util.RelativeDateFormat;
import com.itheima.vo.CommentVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    VideoService videoService;

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    private CommentService commentService;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer server;

    @DubboReference
    private FocusUserService focusUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MqMessageManager mqMessageManager;

    @Cacheable(value = "tanhua", key = "#userId+'_'+#pageNum+'_'+#pageSize", unless = "#result.counts==0")
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.远程调用videoservice查询数据
        PageBeanVo pageBeanVo = videoService.findRecommendVideoByPage(userId, pageNum, pageSize);

        //2.获取分页数据中videoList,遍历集合,获取每个video,获取发布者id,获取发布者userInfo
        List<VideoVo> voList = new ArrayList<>();

        List<Video> items = (List<Video>) pageBeanVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            for (Video video : items) {
                //获取发布者id,获取发布者userInfo
                UserInfo userInfo = userInfoService.findByUserId(video.getUserId());

                //3.将每个video和userInfo封装videoVo,将每个vo放入voList中
                VideoVo vo = new VideoVo();

                //先封装userInfo,再封装video
                vo.setUserInfo(userInfo);
                vo.setVideo(video);

                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER,userId,video.getUserId()))){
                    vo.setHasFocus(1);
                }

                voList.add(vo);
            }
        }

        //4.将voList设置给pageBeanVo且返回
        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    // 发布视频
    @CacheEvict(value = "tanhua", key = "#userId+'_*'")
    public void save(Long userId, MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.将封面和视频上传到FastDFS上,获取路径
        StorePath coverPath = client.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(), FileUtil.extName(videoThumbnail.getOriginalFilename()), null);
        StorePath videoPath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);

        //2.创建video对象,封装video
        Video video = new Video();

        video.setCreated(System.currentTimeMillis());
        video.setUserId(userId);
        video.setPicUrl(server.getWebServerUrl() + coverPath.getFullPath());
        video.setVideoUrl(server.getWebServerUrl() + videoPath.getFullPath());

        System.out.println(video.getVideoUrl());
        System.out.println(video.getPicUrl());

        //3.远程调用service完成保存操作
        videoService.save(video);
    }

    // 关注
    @CacheEvict(value = "tanhua", allEntries = true)
    public void focusUser(Long focusUserId) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.封装focusUser
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);
        focusUser.setCreated(System.currentTimeMillis());

        //3.远程调用service完成保存
        focusUserService.save(focusUser);

        //4.保存关注的标识(redis) // focus_user:99_7
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId), "1");
    }

    //取关
    @CacheEvict(value = "tanhua", allEntries = true)
    public void unFocusUser(Long focusUserId) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.远程调用service完成删除
        focusUserService.delete(userId, focusUserId);

        //3.删除关注的标识(redis)
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER, userId, focusUserId));
    }


    @CacheEvict(value = "videos",allEntries = true)
    /*点赞*/
    public void like(ObjectId id) {
        //mq发送信息
        mqMessageManager.sendLogService(UserHolder.get().getId(), "0302","Video",id.toHexString());
        //获取当前用户id
        Long userId = UserHolder.get().getId();
        //查看redis中是否点赞
        String key = ConstantUtil.VIDEO_LIKE + UserHolder.get().getId();
        String hashKey = String.valueOf(id);
        String isOne = (String) stringRedisTemplate.opsForHash().get(key, hashKey);
        if (StrUtil.isEmpty(isOne)){
            Comment comment=new Comment();
            //封装类型
            comment.setCommentType(CommentType.LIKE.getType());
            //设置动态id
            comment.setPublishId(id);
            //设置创建时间
            comment.setCreated(System.currentTimeMillis());
            //点赞人id
            comment.setUserId(userId);
            commentService.saveVideoLike(comment);
            stringRedisTemplate.opsForHash().put(key,hashKey,"1");
        }
    }

    @CacheEvict(value = "videos",allEntries = true)
    /*取消点赞*/
    public void dislike(ObjectId id) {
        //mq发送信息
        mqMessageManager.sendLogService(UserHolder.get().getId(), "0303","Video",id.toHexString());
        //获取当前用户id
        Long userId = UserHolder.get().getId();
        //查看redis中是否点赞
        String key = ConstantUtil.VIDEO_LIKE + UserHolder.get().getId();
        String hashKey = String.valueOf(id);
        String isOne = (String) stringRedisTemplate.opsForHash().get(key, hashKey);
        if (StrUtil.isNotEmpty(isOne)){
            stringRedisTemplate.opsForHash().delete(key,hashKey);
            commentService.disVideoLike(id,userId);
        }
    }

    //评论列表
    public PageBeanVo commentsPage(Integer page, Integer pagesize, ObjectId id) {
        //mq发送信息
        mqMessageManager.sendLogService(UserHolder.get().getId(), "0205","comment",null);
        //查看动态被评论信息
        List<Comment> commentList=commentService.findCommentByMovementId(page,pagesize,id.toHexString());
        List<CommentVo> commentVoList=new ArrayList<>();
        for (Comment comment : commentList) {
            //发评论者的id
            Long userId = comment.getUserId();
            CommentVo commentVo=new CommentVo();
            UserInfo userInfo = userInfoService.selectUser(userId);
            commentVo.setId(comment.getId().toHexString());
            commentVo.setContent(comment.getContent());
            commentVo.setAvatar(userInfo.getAvatar());
            commentVo.setNickname(userInfo.getNickname());
            commentVo.setCreateDate(RelativeDateFormat.format(new Date(comment.getCreated())));
            commentVo.setLikeCount(comment.getLikeCount());
            //获取当前用户的id
            Long nowId = UserHolder.get().getId();
            //判断当前用户是否点赞
            if (comment.getUserId().equals(nowId)){
                Integer like=commentService.findMyLike(nowId,comment.getPublishId());
                commentVo.setHasLiked(like);
                commentVoList.add(commentVo);
            }else {
                commentVoList.add(commentVo);
            }
        }
        long count = commentList.size();

        return new PageBeanVo(page,pagesize,count,commentVoList);
    }

    //发布评论
    @CacheEvict(value = "videos",allEntries = true)
    public void sendComments(ObjectId id,String comment) {
        //mq发送信息
        mqMessageManager.sendLogService(UserHolder.get().getId(), "0304","Video",id.toHexString());
        //获取当前用户ia
        Long userId = UserHolder.get().getId();
        Comment newComment=new Comment();
        newComment.setPublishId(id);
        newComment.setContent(comment);
        newComment.setCommentType(CommentType.COMMENT.getType());
        newComment.setCreated(System.currentTimeMillis());
        newComment.setUserId(userId);
        newComment.setLikeCount(0);
        commentService.saveVideoComment(newComment);
    }
}
